<?php
/**
 * 榜单管理
 */
namespace Beerus\Modules\DesignerRanking\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerRanking\Actions\EditScore;
use Doraemon\cache\Designer\FlowPool as cFlowPool;
use Doraemon\model\Article;
use Doraemon\model\Designer;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerRanking\DesignerRanking;
use Doraemon\model\DesignerRanking\DesignerRankingChange;
use Beerus\Modules\DesignerRanking\Actions\BatchRemove;
use Doraemon\model\DesignerRanking\DesignerRankingChangeLog;
use Doraemon\model\DesignerRanking\DesignerRankingMonth;
use Doraemon\model\LocalRank\LocalRank as mLocalRank;
use Doraemon\model\Member;
use Doraemon\pockets\constInterface\LocalRank;
use Doraemon\service\DesignerRanking\Ranking;
use Doraemon\tools\ActionLog;
use Doraemon\tools\BackendTool;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;

class RankingController extends Controller {
    const PAGE_SIZE = 10;

    public function list(Request $request, Content $content) {
        $list = DesignerRankingMonth::getNeedAuditList();
        foreach ($list as &$item) {
            $item['can_audit'] = true;
            if (!DesignerRanking::isExistRankingMonth($item['ranking_month'])) {
                $item['can_audit'] = false;
            }
        }
        $gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->column('id');
                $grid->column('ranking_month', '榜单号')->display(function () {
                    if ($this->can_audit) {
                        $html = "<a href='/admin/DesignerRanking/rank/list/{$this->ranking_month}'>{$this->ranking_month}</a>";
                    } else {
                        $html = $this->ranking_month . '「数据暂未生成，暂无法审核」';
                    }
                    return $html;
                });
                $grid->disableActions();

            });

        return $content->header('榜单审核管理')->row($gridList);
    }

    public function rankList(
        Request $request,
        Content $content,
        $rankingMonth,
        $firstRank = '',
        $secondRank = '',
        $thirdRank = ''
    )
    {
        Admin::script($this->setScript());
        $rankingList = DesignerRanking::getMainRankingNameListByRankingMonth($rankingMonth);
        // 根据ranking_sort排序
        $rankingSortArr = array_column($rankingList,'ranking_sort');
        array_multisort($rankingSortArr ,SORT_ASC, $rankingList);
        $mainRankingList = $rankingList ? array_column($rankingList, 'main_ranking_name') : [];
        // 查询城市
        $rankingCityList = DesignerRanking::getCityList($rankingMonth);
        $rankingCityIds = array_unique($rankingCityList);
        sort($rankingCityIds);
        if (empty($firstRank)) {
            $firstRank = $rankingCityIds[0];
        }
        if (empty($secondRank)) {
            $secondRank = $rankingList[0]['main_ranking_name'];
        }
        $thirdList = [];
        if ($mainRankingList) {
            foreach ($rankingList as $mainRankItem) {
                $thirdList[$mainRankItem['main_ranking_name']] = DesignerRanking::getSubRankingNameListByRankingMonth($rankingMonth, $mainRankItem['main_ranking_name']);
            }
            // 根据ranking_sort排序
            foreach ($thirdList as &$thirdRankingItem) {
                $rankingSortArr = array_column($thirdRankingItem,'ranking_sort');
                array_multisort($rankingSortArr ,SORT_ASC, $thirdRankingItem);
            }
            unset($thirdRankingItem);
        }
        $childTab = new Tab();
        foreach ($rankingList as $secondRanking) {
            if (empty($thirdList[$secondRanking['main_ranking_name']])) {
                continue;
            }
            // 三级
            $thirdChild = new Tab();
            foreach ($thirdList[$secondRanking['main_ranking_name']] as $thirdRanking) {
                // 查看该榜单下是否小于3个，小于3个则忽略展示该榜单
                $rankingUids = DesignerRanking::getAllRankingDesignerUidsList($rankingMonth, $firstRank, $secondRank, $thirdRanking['sub_ranking_name']);
                $rankingCnt = count($rankingUids);
                if ($rankingCnt < 3) {
                    continue;
                }
                $removeUidCnt = DesignerRankingChange::getRemoveDesignerCnt($rankingMonth, $thirdRanking['sub_ranking_name'], $firstRank, $rankingUids);
                if ($rankingCnt - $removeUidCnt < 3) {
                    continue;
                }
                if (!$thirdRank) {
                    $thirdRank = $thirdRanking['sub_ranking_name'];
                }
                if ($thirdRanking['sub_ranking_name'] === $thirdRank) {
                    $thirdChild->add("3-{$thirdRanking['sub_ranking_name']}", $this->getList($rankingMonth, $thirdRank, $secondRank, $firstRank), true);
                } else {
                    $thirdChild->add("3-{$thirdRanking['sub_ranking_name']}", '');
                }
            }
            //二级
            if ($secondRanking['main_ranking_name'] === $secondRank) {
                $childTab->add("2-{$secondRanking['main_ranking_name']}", $thirdChild, true);
            } else {
                $childTab->add("2-{$secondRanking['main_ranking_name']}", $thirdChild);
            }
        }
        // 一级
        $tab = new Tab();
        foreach ($rankingCityIds as $rankingCityId) {
            // 每个城市榜单下的个数小于三则不展示
            $everyRankingCntList = DesignerRanking::getEveryRankingCnt($rankingMonth, $rankingCityId);
            $isRemainFlag = false;
            foreach ($everyRankingCntList as $rankingCnt) {
                if ($rankingCnt['cnt'] >= 3) {
                    $isRemainFlag = true;
                    break;
                }
            }
            if (!$isRemainFlag) {
                continue;
            }
            $active = $firstRank === $rankingCityId ? true : false;
            //$cityName = Area::locationId2location($rankingCityId);
			$cityName = Region::getNameByCode($rankingCityId);
            $tab->add("1-{$rankingCityId}-{$cityName}", $childTab, $active);
        }

        Admin::html("<input type='hidden' class='rankingMonth' value='" . $rankingMonth . "'>");
        Admin::html("<input type='hidden' class='thirdRank' value='" . $thirdRank . "'>");
        Admin::html("<input type='hidden' class='secondRank' value='" . $secondRank . "'>");
        Admin::html("<input type='hidden' class='firstRank' value='" . $firstRank . "'>");

        $header = '第'.$rankingMonth.'期榜单';
        $content->row($tab);
        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(['text' => '榜单审核'], ['text' => $header]);
    }

    /*设置scirpt
    *
    * */
    private function setScript()
    {
        $decoCompanyUserType = DesignerRankingChangeLog::USER_TYPE_DECO_COMPANY;
        $transferDecoCompanyType = DesignerRankingChangeLog::USER_TYPE_TRANSFORM_COMPANY;
        return <<<SCRIPT
         $('.nav-tabs li').click(function(e){
              tabName = e.target.innerText.split('-');
              console.log(tabName);
              var rankMonth = $('.rankingMonth').val();
              if (tabName[0] == 1) {
                 var firstRank = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/rank/list/'+rankMonth+'/'+firstRank)
              } else if (tabName[0] == 2) {
                 var firstRank = $('.firstRank').val();
                 var secondRank = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/rank/list/'+rankMonth+'/'+firstRank+'/'+secondRank)
              } else {
                 var firstRank = $('.firstRank').val();
                 var secondRank = $('.secondRank').val();
                 var thirdRank = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/rank/list/'+rankMonth+'/'+firstRank+'/'+secondRank+'/'+thirdRank)
              }
        });
       
       $('.trash-rank').unbind('click').click(function(){
            var designerUid= $(this).data('uid');
            var rankingMonth = $('.rankingMonth').val();
            var firstRank = $('.firstRank').val();
            var secondRank = $('.secondRank').val();
            var thirdRank = $('.thirdRank').val();
            layer.confirm('确定要踢出榜单么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/DesignerRanking/rank/designer/'+ rankingMonth +'/' + firstRank +'/' + secondRank + '/' +thirdRank+'/'+designerUid+'/remove';
                let params = {};
                $.post(url, params , function (result) {
                    console.log(result)
                    if (result.status == true) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 1000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
        $('.edit-score').unbind('click').click(function(){
            var uid= $(this).data('uid');
            var nick= $(this).data('nick');
            var rankingMonth = $(this).data('ranking_month');
            var areaCode = $(this).data('area_code');
            var areaName = $(this).data('area_name');
            var mainRankingName = $(this).data('main_ranking_name');
            var subRankingName = $(this).data('sub_ranking_name');
            var subRankingId = $(this).data('sub_ranking_id');
            var userType = $(this).data('user_type');
            var toDecoCompany = $(this).data('to_deco_company');
            var oldRankingScore = $(this).data('ranking_score');
            var oldRankingNo = $(this).data('ranking_no');
            layer.prompt({
               formType: 0,
               value: '',
               title: '输入新的分数，最长允许10个字符，包括小数点',
               },
               function(value, indexOuter, elem) {
                    newScore = value;
                    if ($.isNumeric(newScore) == false) {
                        layer.msg('必须是数字！');
                        return;
                    }
                    if (newScore <= 0 || newScore > 100) {
                        layer.msg('分数范围不在0-100之间');
                        return;
                    }
                    if (newScore.length > 10) {
                        layer.msg('分数长度超限，最长不得超过10个字符哦，请注意');
                        return;
                    }
                    /*
                    if (userType != {$transferDecoCompanyType}&& userType != {$decoCompanyUserType}
                    ) {
                        layer.msg('只能更改装企或待转装企的分数！');
                        return;
                    }
                    */
                    if (newScore == oldRankingScore) {
                        layer.msg('分数未更改！');
                        return;
                    }
                    let urlGetPos = '/admin/DesignerRanking/rankingPosition/get';
                    let paramsGetPos = {
                        main_ranking_name:mainRankingName,
                        sub_ranking_name:subRankingName,
                        area_code:areaCode,
                        ranking_month:rankingMonth,
                        ranking_score:value,
                        uid:uid,
                    };
                    $.post(urlGetPos, paramsGetPos, function (result) {
                        console.log(result);
                        if (result.status == true) {
                            // 实时获取排名
                            let tip = '调整后的排名为第'+result.data+'名';
                            layer.confirm(tip, function(indexInner, layero) {
                                let url = '/admin/DesignerRanking/rankingScore/save';
                                let params = {
                                    main_ranking_name:mainRankingName,
                                    sub_ranking_name:subRankingName,
                                    area_code:areaCode,
                                    ranking_month:rankingMonth,
                                    ranking_score:value,
                                    uid:uid,
                                    ranking_no:result.data,
                                    old_ranking_no:oldRankingNo,
                                    to_deco_company:toDecoCompany,
                                    user_type:userType,
                                    old_ranking_score:oldRankingScore
                                };
                                $.post(url, params, function (result) {
                                    console.log(result);
                                    if (result.status == true) {
                                        layer.close(indexInner);
                                        layer.close(indexOuter);
                                        parent.window.location.reload();
                                    } else {
                                        layer.msg(result.message);
                                    }
                                });
                            });
                        } else {
                            layer.msg(result.message);
                        }
                    });
               }
           );
           $('.layui-layer-content').prepend('<p>用户信息: '+nick+'('+uid+')</p><p>所在榜单: '+areaName+'>>'+mainRankingName+'>>'+subRankingName+'</p><p>原先排名: 第'+oldRankingNo+'名</p><p>原先分数: '+oldRankingScore+'分</p>');
        });
SCRIPT;
    }

    public function getList($rankingMonth, $thirdRank, $secondRank, $firstRank) {
        // 获取已剔除榜单uid
        $map = [
            'ranking_month' => $rankingMonth,
            'main_ranking_name' => $secondRank,
            'sub_ranking_name' => $thirdRank,
	        'area_code' => $firstRank,
            'data_status' => DesignerRanking::STATUS_NORMAL,
            'ORDER' => [
                'ranking_score' => 'DESC'
            ],
            'LIMIT' => 20
        ];
        $allRemoveDesignerUids = DesignerRankingChange::getAllRemoveDesignerUid($rankingMonth, $secondRank, $thirdRank);
        if ($allRemoveDesignerUids) {
            $map['designer_uid[!]'] = $allRemoveDesignerUids;
        }
        $list = DesignerRanking::select('*', $map);
        Ranking::adminFormatList($list, $rankingMonth);
        $gridModel = new pGridDataModel($list, 20, [
            'keyName' => 'designer_uid'
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($thirdRank, $secondRank, $firstRank, $rankingMonth) {
            $grid->tools(function($tools) use ($rankingMonth, $thirdRank, $firstRank) {
                $previewUrl = Hhzurl::getDomain() . "/designer/recommend-list?ranking_month={$rankingMonth}&sub_ranking_name={$thirdRank}&lid={$firstRank}&isPreview=1";
                $linkUrl = '<a href="javascript:layer.open({
                    type: 2,
                    title: \'预览\', 
                    maxmin: true, 
                    area: [\'350px\', \'700px\'],
                    fixed: false,
                    content: \''.$previewUrl.'\'
                  });">预览</a>';
                $tools->append($linkUrl);
            });
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->column('ranking_name', '榜单名称')->display(function () use ($thirdRank) {
                return $thirdRank.'榜';
            });
            $grid->column('ranking_no', '排名');
            $grid->column('designer_uid', 'UID');
            $grid->column('designer_name', '设计师')->display(function() {
                $designerAuthStatusTxt = '';
                if ($this->designer_auth_status != DesignerAuth::STATUS_AUDIT_PASS_SECOND) {
                    $designerAuthStatusTxt = "<span style='color:#dd4b39'>（未认证）</span>";
                }
                return $this->designer_name . $designerAuthStatusTxt;
            });
            $grid->column('user_type_txt', '身份');
            $grid->column('flow_pool', '流量池')->display(function () {
                $color = $this->flow_pool == 'D' ? 'style="color:red"' : '';
                return "<span {$color}>{$this->flow_pool}</span>";
            });
            $grid->column('operator_name', '对接运营');
            $grid->column('ranking_article_list', '案例')->display(function () use ($thirdRank, $secondRank, $firstRank, $rankingMonth) {
                if($this->sub_ranking_name == LocalRank::EVALUATE ){
                    $aEvaluateInfo =  $this->evaluate_info;
                    $intro = "<span style='color:#dd4b39'>业主评价</span>";
                    $content = $aEvaluateInfo['content'];
                    $img = '';
                    if(is_array($aEvaluateInfo['image_list'])){
                        foreach ($aEvaluateInfo['image_list'] as $key=> $image){
                            if($image['thumb_pic_url']){
                                $img.= "<a href=''><img width='100' height='100' src='{$image['thumb_pic_url']}'></a>";
                            }
                            if($key % 5 == 0 && $key != 0){
                                $img.= "<br/>";

                            }
                        }
                    }
                    $articleRet[] = implode('<br/>', [$intro, $img, $content]);
                }else{
                    foreach ($this->ranking_article_list as $article) {
                        $articleTxt = "整屋ID：{$article['article_id']}";
                        if ($article['article_status'] != Article::STATUS_SUCCESS) {
                            $articleTxt .= "<span style='color:#dd4b39'>(" . Article::STATUS_MAP[$article['article_status']] . ")</span";
                        }
                        $img = "<a href='/admin/DesignerRanking/rank/articleCover/jump/{$rankingMonth}/{$firstRank}/{$secondRank}/{$thirdRank}/{$article['article_id']}'><img width='100' height='100' src='{$article['cover_pic']}'></a>";
                        $title = "<a href='/admin/DesignerRanking/rank/articleAudit/jump/{$rankingMonth}/{$article['article_id']}'>{$article['title']}</a>";
                        $intro = $article['intro'];
                        $articleRet[] = implode('<br/>', [$img, $articleTxt, $title, $intro]);
                    }
                }
                return implode('<br/><br/>', $articleRet);
            });
            $grid->column('expire_time', '认证到期时间');
            $grid->column('ranking_no_list', '在榜情况')->display(function () {
                $aRankingNoTxtList = [];
                foreach ($this->ranking_no_list as $aRankingNoItem) {
                    $aRankingNoTxtList[] = $aRankingNoItem['main_ranking_name'] . '-' . $aRankingNoItem['sub_ranking_name'] . '-top' . $aRankingNoItem['ranking_no'];
                }
                return implode('<br>', $aRankingNoTxtList);
            });
            $grid->column('ranking_score', '推荐值');

            $grid->column("ranking_status", '榜单状态')->display(function () {
                if ($this->ranking_status == Ranking::RANKING_AUDITING) {
                    return "<span style='color:#00c0ef'>审核中</span>";
                }
                if ($this->ranking_status == Ranking::RANKING_EXPIRE) {
                    return "<span style='color:#dd4b39'>已过期</span>";
                }
                if ($this->ranking_status == Ranking::RANKING_SHOW) {
                    return "<span style='color:#00a65a'> 上榜中</span>";
                }
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) use ($rankingMonth) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($this->row['ranking_status'] != Ranking::RANKING_EXPIRE) {
                    $actions->append('<a class=\'fa fa-trash trash-rank\' data-uid="' . $this->row["designer_uid"] . '" data-type="' . $rankingMonth . '"  data-ranking_month ="' . $this->row['ranking_month'] . '" >踢出榜单</a>');
                }
                // 审核中且装修公司和待转装修公司的才显示修改分数功能
                if ($this->row['ranking_status'] == Ranking::RANKING_AUDITING
                    // && ($this->row['user_type'] == Member::AUTH_DECO_COMPANY || ($this->row['user_type'] == Member::AUTH_USER_DESIGNER && $this->row['to_deco_company'] == Designer::TO_DECO_COMPANY_YES))
                    ) {
                    $areaName = Region::getNameByCode($this->row['area_code']);
                    $userType = $this->row['user_type'] == Member::AUTH_DECO_COMPANY ? DesignerRankingChangeLog::USER_TYPE_DECO_COMPANY : DesignerRankingChangeLog::USER_TYPE_TRANSFORM_COMPANY;
                    $html = '<a class=\'fa fa-edit edit-score\' '
                        .' data-uid="' . $this->row["designer_uid"] . '" '
                        .' data-nick="' . $this->row["designer_name"] . '" '
                        .' data-ranking_month ="' . $this->row['ranking_month'] . '" '
                        .' data-area_code ="' . $this->row['area_code'] . '" '
                        .' data-area_name ="' . $areaName . '" '
                        .' data-main_ranking_name ="' . $this->row['main_ranking_name'] . '" '
                        .' data-sub_ranking_name ="' . $this->row['sub_ranking_name'] . '" '
                        .' data-sub_ranking_id ="' . $this->row['sub_ranking_id'] . '" '
                        .' data-user_type="' . $userType . '" '
                        .' data-to_deco_company ="' . $this->row['to_deco_company'] . '" '
                        .' data-ranking_score ="' . $this->row['ranking_score'] . '" '
                        .' data-ranking_no ="' . $this->row['ranking_no'] . '" '
                        .'>调整分数</a>';
                    $actions->append($html);
                }
            });
        });
        if (Ranking::getRankingStatus($rankingMonth) != Ranking::RANKING_AUDITING) {
            $listGrid->disableRowSelector();
        } else {
            $listGrid->batchActions(function (Grid\Tools\BatchActions $batch) use (
                $rankingMonth,
                $firstRank,
                $secondRank,
                $thirdRank
            ) {
                $batch->disableDelete();
                $batch->add('批量剔除', new BatchRemove($rankingMonth, $firstRank, $secondRank, $thirdRank));
            });
        }
        return $listGrid->render();
    }

    public function batchRemove(Request $request) {
        $aUid = $request->post('ids');
        $iRankingMonth = $request->post('ranking_month');
        $iRankingCityAreaCode = $request->post('ranking_city_area_code');
        $sMainRankingName = $request->post('main_ranking_name');
        $sSubRankingName = $request->post('sub_ranking_name');
        if (Ranking::getRankingStatus($iRankingMonth) != Ranking::RANKING_AUDITING) {
            return response()->json([
                'status' => false,
                'message' => "非审核期间不开放批量剔除",
            ]);
        }
        if (empty($aUid)) {
            return response()->json([
                'status' => false,
                'message' => "未选择任何内容",
            ]);
        }
        $iOldRankCityId = Region::getOldCodeByCode($iRankingCityAreaCode) ?? '';
        $aInsertData = [];
        foreach ($aUid as $iUid) {
            $aInsertData[] = [
                'ranking_month' => $iRankingMonth,
                'main_ranking_name' => $sMainRankingName,
                'sub_ranking_name' => $sSubRankingName,
                'ranking_city' => $iOldRankCityId,
                'area_code' => $iRankingCityAreaCode,
                'assoc_type' => DesignerRankingChange::ASSOC_TYPE_REMOVE_DESIGNER,
                'assoc_id' => $iUid,
                'admin_id' => Admin::user()->id,
                'add_time' => time(),
                'edit_time' => time()
            ];
        }
        if (!DesignerRankingChange::batchAddData($aInsertData)) {
            return response()->json([
                'status' => false,
                'message' => "批量剔除失败",
            ]);
        }
        $aUpdateCondition = [
            'ranking_month' => $iRankingMonth,
            'main_ranking_name' => $sMainRankingName,
            'sub_ranking_name' => $sSubRankingName,
            'area_code' => $iRankingCityAreaCode,
            'designer_uid' => $aUid,
        ];
        if (!DesignerRanking::update(['data_status'=>DesignerRanking::STATUS_DELETE], $aUpdateCondition)) {
            return response()->json([
                'status' => false,
                'message' => "榜单数据状态更新失败",
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => "批量剔除成功",
        ]);
    }

    public function editArticle(
        Request $request,
        Content $content,
        $rankingMonth,
        $firstRank = '',
        $secondRank = '',
        $thirdRank = '',
        $aid = 0) {
        $data = Article::getArticleInfo($aid);
        // 查询是否换过封面
        $changeCoverPicId = DesignerRankingChange::getChangeCover(
            $rankingMonth,
            $secondRank,
            $thirdRank,
            $aid
        );
        $data['cover_pic_id'] = !empty($changeCoverPicId) ? $changeCoverPicId['cover_pic_id'] : $data['cover_pic_id'];
        $data['ranking_month'] = $rankingMonth;
        $form = new Form($data);
        $form->text('ranking_month', '榜单期号')->readOnly();
        $form->text('aid', '整屋ID')->readOnly();
        $form->text('title', '整屋标题')->readOnly();
        $form->imgUpload('cover_pic_id', '整屋封面', false,
            [
                'imgType' => ImgUrl::APPTYPE_APP,
                'imgSize' => ImgUrl::IMAGE_SIZE_SQ_THUMB
            ])
            ->required();
        $form->confirm('确定提交吗？');
        $form->action("/admin/DesignerRanking/rank/article/{$rankingMonth}/{$firstRank}/{$secondRank}/{$thirdRank}/save");

        $header = '整屋封面修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '榜单审核管理'],
                ['text' => '整屋封面修改'],
            )->row($tab);
    }

    public function saveArticle(Request $request,
                                $rankingMonth,
                                $firstRank = '',
                                $secondRank = '',
                                $thirdRank = '') {
        if (Ranking::getRankingStatus($rankingMonth) == Ranking::RANKING_EXPIRE) {
            $error = new MessageBag(['title' => '该榜单已过期，不支持修改']);
            return back()->with(compact('error'));
        }
        $request = $request->all();
        // 先查询是否已经替换过封面
        $changeCoverPicId = DesignerRankingChange::getChangeCover($rankingMonth, $secondRank, $thirdRank, $request['aid']);
        $oldCoverPicId = $changeCoverPicId;
        if (empty($oldCoverPicId)) {
            $articleInfo = Article::getArticleInfo($request['aid']);
            $oldCoverPicId = $articleInfo['cover_pic_id'];
        }
        if ($oldCoverPicId != $request['cover_pic_id']) {
            if (empty($changeCoverPicId)) { // 新增
                if (!DesignerRankingChange::addInfo([
                    'cover_pic_id' => $request['cover_pic_id'],
                    'ranking_month' => $rankingMonth,
                    'main_ranking_name' => $secondRank,
                    'sub_ranking_name' => $thirdRank,
                    'assoc_type' => DesignerRankingChange::ASSOC_TYPE_CHANGE_COVER,
                    'assoc_id' => $request['aid'],
                    'admin_id' => Admin::user()->id
                ])) {
                    $error = new MessageBag(['title' => '替换失败1']);
                    return back()->with(compact('error'));
                }
            } else {
                if (!DesignerRankingChange::updateInfo([
                    'cover_pic_id' => $request['cover_pic_id'],
                    'admin_id' => Admin::user()->id
                ], [
                    'ranking_month' => $rankingMonth,
                    'main_ranking_name' => $secondRank,
                    'sub_ranking_name' => $thirdRank,
                    'assoc_type' => DesignerRankingChange::ASSOC_TYPE_CHANGE_COVER,
                    'assoc_id' => $request['aid']
                ])) {
                    $error = new MessageBag(['title' => '替换失败2']);
                    return back()->with(compact('error'));
                }
            }
        }
        $success = new MessageBag(['title' => '修改成功']);
        $redirectUrl = "/admin/DesignerRanking/rank/list/{$rankingMonth}";
        if (!empty($firstRank)) {
            $redirectUrl .= "/{$firstRank}";
        }
        if (!empty($secondRank)) {
            $redirectUrl .= "/{$secondRank}";
        }
        if (!empty($thirdRank)) {
            $redirectUrl .= "/{$thirdRank}";
        }
        return redirect($redirectUrl)->with(compact('success'));
    }

    public function removeDesigner(
        Request $request,
        $rankingMonth,
        $firstRank,
        $secondRank,
        $thirdRank,
        $designerUid
    ) {
        /**
         * 审核中：审核期的状态，从榜单生成至正式展示给用户的期间。支持运营操作替换封面，剔除设计师，支持链接跳转案例修改标签
         * 上榜中：过了审核期，正式展示给用户的期间。支持运营替换封面，剔除设计师
         * 已过期：不再展示给用户的期间。以上功能都不支持
         */
        $rankingStatus = Ranking::getRankingStatus($rankingMonth);
        if ($rankingStatus == Ranking::RANKING_EXPIRE) {
            return response()->json([
                'status' => false,
                'message' => "该榜单已过期，不支持修改",
            ]);
        }
        $rank_city = Region::getOldCodeByCode($firstRank) ?? '';
        // 通过id查设计师uid
        $data = [
            'ranking_month' => $rankingMonth,
            'main_ranking_name' => $secondRank,
            'sub_ranking_name' => $thirdRank,
            'ranking_city' => $rank_city,
            'area_code' => $firstRank,
            'assoc_type' => DesignerRankingChange::ASSOC_TYPE_REMOVE_DESIGNER,
            'assoc_id' => $designerUid,
            'admin_id' => Admin::user()->id
        ];
        if (!DesignerRankingChange::addInfo($data)) {
            return response()->json([
                'status' => false,
                'message' => "移除失败1",
            ]);
        }
        // 更新榜单数据状态
        $updateCondition = [
            'ranking_month' => $rankingMonth,
            'main_ranking_name' => $secondRank,
            'sub_ranking_name' => $thirdRank,
            'area_code' => $firstRank,
            'designer_uid' => $designerUid,
        ];
        // 获取榜单id
        $aRankingInfo = DesignerRanking::getByWhere($updateCondition);
        $iRankingId = $aRankingInfo['sub_ranking_id'];
        if (!DesignerRanking::update(['data_status'=>DesignerRanking::STATUS_DELETE], $updateCondition)) {
            return response()->json([
                'status' => false,
                'message' => "移除失败2",
            ]);
        }
        // 上榜中的才刷新缓存
        if ($rankingStatus == Ranking::RANKING_SHOW) {
            Ranking::removeDesignerFromRankingCache($designerUid, $rankingMonth, $iRankingId, $firstRank);
        }
        ActionLog::log($designerUid, [
            'designer_uid' => $designerUid,
            'main_ranking_name' => $secondRank,
            'sub_ranking_name' => $thirdRank,
            'ranking_city' => $rank_city,
            'area_code' => $firstRank,
            'admin_id' => Admin::user()->id,
            'op' => 'remove'
        ], ActionLog::BEERUS_RANKING_ACTION);
        return response()->json([
            'status' => true,
            'message' => "移除成功",
        ]);
    }

    public function jumpArticleAudit(
        Request $request,
        $rankingMonth,
        $articleId
    ) {
        if (Ranking::getRankingStatus($rankingMonth) == Ranking::RANKING_EXPIRE) {
            $error = new MessageBag(['title' => '该榜单已过期，不支持跳转']);
            return back()->with(compact('error'));
        }
        if (Ranking::getRankingStatus($rankingMonth) == Ranking::RANKING_SHOW) {
            $error = new MessageBag(['title' => '该榜单在上榜中，不支持跳转']);
            return back()->with(compact('error'));
        }
        $jumpUrl = "https://frieza.haohaozhu.me/admin/article/select/audit/{$articleId}";
        return redirect($jumpUrl);
    }

    public function jumpArticleCover(
        Request $request,
        $rankingMonth,
        $firstRank = '',
        $secondRank = '',
        $thirdRank = '',
        $articleId
    ) {
        if (Ranking::getRankingStatus($rankingMonth) == Ranking::RANKING_EXPIRE) {
            $error = new MessageBag(['title' => '该榜单已过期，不支持跳转']);
            return back()->with(compact('error'));
        }
        $jumpUrl = "/admin/DesignerRanking/rank/article/{$rankingMonth}/{$firstRank}/{$secondRank}/{$thirdRank}/{$articleId}/edit";
        return redirect($jumpUrl);
    }

    /**
     * 获取当前排名
     */
    public function getCurRankingPosition(Request $request) {
        $designerUid = $request->post('uid');
        $rankingMonth = $request->post('ranking_month');
        $mainRankingName = $request->post('main_ranking_name');
        $subRankingName = $request->post('sub_ranking_name');
        $areaCode = $request->post('area_code');
        $rankingScore = $request->post('ranking_score');
        $allRemoveDesignerUids = DesignerRankingChange::getAllRemoveDesignerUid($rankingMonth, $mainRankingName, $subRankingName);
        $list = DesignerRanking::getHasRemoveRankingDesignerList($rankingMonth, $areaCode, $mainRankingName, $subRankingName, $allRemoveDesignerUids);
        $uidScoreMap = array_column($list, 'ranking_score', 'designer_uid');
        $uidScoreMap[$designerUid] = $rankingScore;
        arsort($uidScoreMap);
        $scoreList = array_values($uidScoreMap);
        $pos = array_search($rankingScore, $scoreList);
        return response()->json([
            'status' => true,
            'message' => '排名获取成功',
            'data' => $pos + 1
        ]);
    }

    /**
     * 获取当前排名
     */
    public function saveRankingScore(Request $request) {
        $designerUid = $request->post('uid');
        $userType = $request->post('user_type');
        $toDecoCompany = $request->post('to_deco_company');
        $rankingMonth = $request->post('ranking_month');
        $mainRankingName = $request->post('main_ranking_name');
        $subRankingName = $request->post('sub_ranking_name');
        $areaCode = $request->post('area_code');
        $rankingScore = $request->post('ranking_score');
        $rankingNo = $request->post('ranking_no');
        $oldRankingScore = $request->post('old_ranking_score');
        $oldRankingNo = $request->post('old_ranking_no');
        // 判断参数是否符合要求
        if (!is_numeric($rankingScore)) {
            return response()->json([
                'status' => false,
                'message' => '分数必须为数字！'
            ]);
        }
        if ($rankingScore <= 0 || $rankingScore > 100) {
            return response()->json([
                'status' => false,
                'message' => '分数必须在0-100之间！'
            ]);
        }
        if (strlen($rankingScore) > 10) {
            return response()->json([
                'status' => false,
                'message' => '分数长度超限，最长不得超过10个字符哦，请注意！'
            ]);
        }
        // 检查旧分数
        if ($rankingScore == $oldRankingScore) {
            return response()->json([
                'status' => true,
                'message' => '分数未更改！',
                'data' => $rankingScore
            ]);
        }
        // 检查身份
        if ($userType != DesignerRankingChangeLog::USER_TYPE_TRANSFORM_COMPANY && $userType != DesignerRankingChangeLog::USER_TYPE_DECO_COMPANY
        ) {
            return response()->json([
                'status' => true,
                'message' => '只能更改装企或待转装企的分数！',
                'data' => $rankingScore
            ]);
        }
        // 更改分数
        if (false === DesignerRanking::updateDesignerRankingScore($rankingScore, $rankingMonth, $designerUid, $areaCode, $mainRankingName, $subRankingName)) {
            return response()->json([
                'status' => false,
                'message' => '修改分数失败！',
                'data' => $rankingScore
            ]);
        }
        // 添加调整记录
        $oldData = [
            'ranking_score' => $oldRankingScore,
            'ranking_no' => $oldRankingNo
        ];
        $newData = [
            'ranking_score' => $rankingScore,
            'ranking_no' => $rankingNo
        ];
        if (false === DesignerRankingChangeLog::addChangeScoreLog(
            $rankingMonth,
            $designerUid,
            $userType,
            $mainRankingName,
            $subRankingName,
            $areaCode,
            $oldData,
            $newData,
            Admin::user()->id)
        ) {
            return response()->json([
                'status' => false,
                'message' => '添加更改分数记录失败！',
                'data' => $rankingScore
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => '分数修改成功',
        ]);
    }

    public function history(Request $request, Content $content) {
        $list = DesignerRankingMonth::getHistoryList();
        $gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->column('id');
                $grid->column('ranking_month', '榜单号')->display(function () {
                    $format = [];
                    $format[] = "<a href='/admin/DesignerRanking/rank/list/{$this->ranking_month}'>{$this->ranking_month}</a>";
                    return $format;
                })->label('default');
                $grid->disableActions();
            });

        return $content->header('历史榜单列表')->row($gridList);
    }
}
